import { CHANGED_SELECTION, EDITED_MESSAGE, SEND_MESSAGE } from "../Messenger/action";
import { Action, State } from "../Messenger/interface";

export const initialState: State = {
  selectedId: 0,
  messages: {
    0: "Hello, Taylor",
    1: "Hello, Alice",
    2: "Hello, Bob"
  }
};

export function messengerReducer(state: State, action: Action): State {
  switch (action.type) {
    case CHANGED_SELECTION: {
      return {
        ...state,
        selectedId: action.payload?.contactId ?? state.selectedId
      };
    }
    case EDITED_MESSAGE: {
      return {
        ...state,
        messages: {
          ...state.messages,
          [state.selectedId]: action.payload?.message ?? state.messages[state.selectedId]
        }
      };
    }
    case SEND_MESSAGE: {
      return {
        ...state,
        messages: {
          ...state.messages,
          [state.selectedId]: ""
        }
      };
    }
    default: {
      throw Error("未知 action: " + action.type);
    }
  }
}
